const { Wechaty } = require('wechaty');



// 延时函数，防止检测出类似机器人行为操作
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let QrCode = "";
let Status = "NOT_LOGINED";
// 二维码生成
async function onScan(qrcode, status) {
  const qrcodeImageUrl = [
    'https://api.qrserver.com/v1/create-qr-code/?data=',
    encodeURIComponent(qrcode),
  ].join('');
  QrCode = qrcodeImageUrl;
  Status = "SCANING";
  console.log(`Scan QR Code to login: ${status}\n${qrcodeImageUrl}`);
}

// 登录
async function onLogin(user) {
  Status = "LOGINED"
  console.log(`贴心小助理${user}登录了`);
  const date = new Date()
  console.log(`当前容器时间:${date}`);
  
}

// 登出
function onLogout(user) {
  console.log(`小助手${user} 已经登出`);
  Status = "LOGOUT";
}

// 监听对话
async function onMessage(msg) {
  const contact = msg.talker(); // 发消息人
  const content = msg.text().trim(); // 消息内容
  const room = msg.room(); // 是否是群消息
  const alias = await contact.alias() || await contact.name(); // 发消息人备注
  const isText = msg.type() === bot.Message.Type.Text;
  if (msg.self()) {
    return;
  }
  
  if (room && isText) {
    // 如果是群消息 目前只处理文字消息
    const topic = await room.topic();
    console.log(`群名: ${topic} 发消息人: ${await contact.name()} 内容: ${content}`);
  } else if (isText) {
    // 如果非群消息 目前只处理文字消息
    console.log(`发消息人: ${alias} 消息内容: ${content}`);
    if (content.substr(0, 1) == '?' || content.substr(0, 1) == '？') {
      let contactContent = content.replace('?', '').replace('？', '');
      if (contactContent) {
        let res = await superagent.getRubbishType(contactContent);
        await delay(2000);
        await contact.say(res);
      }
    }
  }
}



const bot = new Wechaty({
  name: 'WechatEveryDay',
  puppet: 'wechaty-puppet-wechat', // 如果有token，记得更换对应的puppet
  // puppetOptions: {
  //   token: '如果有token，填入wechaty获取的token，并把注释放开'
  // }
});

bot.on('scan', onScan);
bot.on('login', onLogin);
bot.on('logout', onLogout);
bot.on('message', onMessage);



function start() {
  Status = "LOGINING"
  bot.start()
  .then(() => {
    console.log('开始登陆微信')
  })
  .catch((e) => {
    Status = "START_ERROR"
    console.error(e)
  });
}




function getLogonoff() {
  return bot.logonoff();
}

function getStatus(){
  console.info("bot-->getStatus", bot.logonoff(), Status)
  if(bot.logonoff()){
    return "LOGINED";
  } else {
    return Status;
  }
}

function getQrCode(){
  return QrCode
}

function getBotInfo(){
  return bot.userSelf()
}

module.exports = {
  getQrCode,
  getStatus,
  getLogonoff,
  getBotInfo,
  start
}
